<template>
  <div class="item">
    <div class="item_i" v-for="item in todoList" :key="item.id">
      <div class="item_left">
        <input type="checkbox" v-model="item.isCheck" />
        <span v-if="item.isEdit">{{ item.todo }}</span>
        <input
          type="text"
          v-model="item.todo"
          v-else
          ref="editInput"
          @blur="blurInp(item.id)"
          @keyup.enter="editInp(item.id)"
          @focus="onfocus($event)"
        />
      </div>
      <div class="item_del">
        <button class="edit" @click="edit(item.id)">编辑</button>
        <button @click="del(item.id)">删除</button>
      </div>
    </div>
  </div>
</template>


<script>
export default {
  // 接受到了list父组件发送来的数据
  props: ['todoList'],
  data() {
    return {
      //isshowEdit: true
    }

  },
  methods: {
    // 点击删除利用子传父传给List组件来删除对应的todo
    del(id) {
      if (confirm('确定要删除吗？'))
        this.$emit('delID', id)
    },
    // 点击编辑，通过id来编辑对应的todo
    edit(id) {
      this.todoList.forEach(todo => {
        if (todo.id === id) {
          todo.isEdit = false
        }
      })
      // 点击编辑获取对应的编辑框的焦点
      this.$nextTick(() => {
        //this.$refs.saveTagInput.$refs.input.focus()
        //console.log(this.$refs.editInput[0].focus())
        this.$refs.editInput[0].focus()
      })
    },
    // 失去焦点重新让input消失，span显示
    blurInp(id) {
      this.todoList.forEach(todo => {
        if (todo.id === id) {
          todo.isEdit = true
        }
      })
    },
    // 监听键盘按下enter按键来控制input的隐藏
    editInp(id) {
      this.todoList.forEach(todo => {
        if (todo.id === id) {
          todo.isEdit = true
        }
      })
    },
    // 监听input获取焦点时选中input的值
    onfocus(e){
        console.log(e)
        e.currentTarget.select()
    }
  }
}
</script>


<style lang="less" scoped>
.item_i:hover {
  background-color: #666;
  color: #fff;
}
.item_i:hover .item_del button {
  display: block;
}
.item_i {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 10px;
  border-bottom: 1px solid #ccc;
  // margin-bottom: 10px;
  box-sizing: border-box;
  // margin: 0 10px;
  // padding: 0 10px;
}
.item_del {
  display: flex;
}
.item_del button {
  background-color: red;
  color: #fff;
  border: none;
  display: none;
}
.item_del .edit {
  background-color: blue;
  margin-right: 10px;
}
</style>